package com.ymj.demoback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ymj.demoback.mapper.UserMapper;
import com.ymj.demoback.model.domain.User;
import com.ymj.demoback.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ymj.demoback.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现类
 */

/**
* @author 33180
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2024-12-20 14:50:46
*/
@Service
@Slf4j
// lombok 的注解，可以使用日志
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
//    注入 mapper
    private UserMapper userMapper;
//    prsf: 可以快速打出 private static final
    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "njx";

    @Override
    public long UserRegister(String userAccount, String userPassword, String checkPassword) {
//        1.校验
        if (StringUtils.isAllBlank(userAccount,userPassword,checkPassword)){
//            TODO 修改为自定义异常
            return -1;
        }
        if (userAccount.length() < 4){
            return -1;
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8){
            return -1;
        }
//        账户不能重复
        if (userAccount.equals(userAccount)){
            return -1;
        }

//        账户不能包含特殊字符(使用正则表达式校验)
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？][`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (!matcher.find()){
            return -1;
        }
//        密码和校验密码相同
        if (!userPassword.equals(checkPassword)){
            return -1;
        }
//        账户不能重复(查一下数据库中有没有重复的)
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            return -1;
        }
//        2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + "mypassword").getBytes());
//        3.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if (!saveResult){
            return -1;
        }
        this.save(user);
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
//        校验
        if (StringUtils.isAllBlank(userAccount,userPassword)){
            return null;
        }
        if (userAccount.length() < 4){
            return null;
        }
        if (userPassword.length() < 8){
            return null;
        }
//        账户不能重复
        if (userAccount.equals(userAccount)){
            return null;
        }

//        账户不能包含特殊字符(使用正则表达式校验)
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？][`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (!matcher.find()){
            return null;
        }
//        2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + "mypassword").getBytes());
//        查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq(userPassword,encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
//        用户不存在
        if (user == null){
            log.info("user login failed,userAccount cannot match userPassword");
            return null;
        }

        long count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            return null;
        }
//        3.用户脱敏
        User safetyUser = getSafetyUser(user);
//        4.记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);

        return safetyUser;
    }

    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser){
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setUpdateTime(originUser.getUpdateTime());
        return safetyUser;
    }
}




